package middleware

import (
	"github.com/gin-gonic/gin"
	"go_pure_admin_api/utils"
	"net/http"
	"strings"
)

func Auth() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取token
		extractToken := c.GetHeader("Authorization")
		if extractToken == "" {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"code": http.StatusUnauthorized, "msg": "请先登录"})
			return
		}
		token := strings.TrimPrefix(extractToken, "Bearer ")
		Claims, err := utils.ParseTokenHs256(token)
		if err != nil {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"code": http.StatusUnauthorized, "msg": "请先登录"})
			return
		}
		c.Set("username", Claims.Username)
		// 检查权限
		if !utils.CheckPermission(Claims, c.Request.URL.Path, c.Request.Method) {
			c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"code": http.StatusForbidden, "msg": "无权限"})
			return
		}
		c.Next()
	}
}
func AuthToken() gin.HandlerFunc {
	return func(c *gin.Context) {
		extractToken := c.GetHeader("Authorization")
		if extractToken == "" {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"code": http.StatusUnauthorized, "msg": "请先登录"})
			return
		}
		token := strings.TrimPrefix(extractToken, "Bearer ")
		Claims, err := utils.ParseTokenHs256(token)
		if err != nil {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"code": http.StatusUnauthorized, "msg": "请先登录"})
			return
		}
		c.Set("username", Claims.Username)
	}
}
